package com.ldl.servlet.admin;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldl.Const;



/**
 * @author Administrator
 * Author : L.D.L
 * E-mail : 1419485293@qq.com
 * Date : 2020年8月4日下午5:07:13
 */
@WebServlet("/code.let")
public class CodeServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Random r = new Random();
		String code = ""+r.nextInt(10)+r.nextInt(10)+r.nextInt(10)+r.nextInt(10);
		request.getSession().setAttribute(Const.CODE_NAME, code);
		int width = 139;
		int height = 48;
		
		BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
		Graphics g = img.getGraphics();
		g.setColor(new Color(255,255,255));
		g.fillRect(0, 0, width, height);
		
		for(int i=0; i<height/2; i++){
			g.setColor(new Color(150+r.nextInt(100),150+r.nextInt(100),150+r.nextInt(100)));
			g.drawLine(0, r.nextInt(height), width, r.nextInt(height));
		}
		
		int fontsize = 34;
		g.setFont(new Font("微软雅黑", Font.BOLD, fontsize));
		int w = width/code.length();
		for(int i=0;i<code.length();i++){
			g.setColor(new Color(50+r.nextInt(150),50+r.nextInt(150),50+r.nextInt(150)));
			g.drawString(code.substring(i,i+1), i*w, height-r.nextInt(height-fontsize));
		}
		
		response.reset();
		response.setContentType("image/jpeg");
//		ImageIO.write(img, "jpg", new File("E:/eclipse/demo/ldl_web_demo3/WebContent/验证.jpg"));
		ImageIO.write(img, "jpg", response.getOutputStream());
		response.flushBuffer();
		
	}
	
}
